import { formEmits, useFormItem } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";
import { useFormItemExam } from "@/views/formgen/components/FormItem/hooks/useExamHook";
import { BasicComponent } from "@/views/formgen/components/GenerateForm/types/form";
import { formOptionLogicHook } from "@/views/formgen/components/GenerateForm/hooks/useFormOptionLogic";
import { nextTick, onMounted, watch } from "vue";

export const selectEmits = [...formEmits, "changeLabel", "next"];

export function useSelect(props: any, emits: any) {
  const examHook = useFormItemExam(<BasicComponent>props.item);

  const { classList } = examHook;

  const formItemHook = useFormItem(props, emits, false);

  const { changeValue, getOptions, updateValue } = formItemHook;

  const { isShowOption, initWatchCheckRule } = formOptionLogicHook;

  const handleChange = (val: any) => {
    classList.value = examHook.getExamClass(changeValue.value, null);
    updateValue(val);
    const label = getOptions().find((item: any) => val == item.value)?.label;
    emits("changeLabel", label);
    nextTick(() => {
      if (val) {
        formItemHook.autoNextPage(emits);
      }
    });
  };

  // 监听options变化 在某些情况选项是异步加载的 会导致加载到默认的选项 导致label值错误
  watch(
    () => props!.item!.config!.options,
    () => {
      const label = getOptions().find((item: any) => changeValue.value == item.value)?.label;
      emits("changeLabel", label);
    },
    {
      deep: true
    }
  );

  // 处理默认值不包含label
  watch(
    () => props.value,
    () => {
      handleChange(props.value);
    }
  );

  onMounted(() => {
    handleChange(changeValue.value);
    // 自动选中逻辑
    initWatchCheckRule(props.item?.vModel as string, (val: any[]) => {
      if (val.length) {
        const options = getOptions().filter((op: any) => val.includes(op.value));
        // 如果已经被选中则不执行 在执行会取消
        if (options) {
          changeValue.value = options[0]?.value;
          handleChange(changeValue.value);
        }
      }
    });
  });

  return { changeValue, classList, handleChange, getOptions, isShowOption };
}
